package com.yang.service.impl;

import java.util.HashSet;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.yang.dao.BaseDAO;
import com.yang.dao.RoleDao;
import com.yang.entity.Permissions;
import com.yang.entity.Roles;
import com.yang.model.Page;
import com.yang.service.PermissionService;
import com.yang.service.RoleService;

/**
 * 描述：角色业务实现类
 * 版本：1.0
 * 作者： 杨建全
 * 创建时间：2016年3月24日  上午9:33:32
 */
@Service
@Transactional
public class RoleServiceImpl implements RoleService {
	@Autowired
	private RoleDao roleDao;
	@Autowired
	private BaseDAO<Roles> baseDao;
	@Autowired
	private PermissionService permissionService;
	
	public Roles createRole(Roles role) {
		return roleDao.createRole(role);
	}

	public Roles updateRole(Roles role) {
		String preStr = role.getPremissionsStr();
		List<Permissions> permissions = permissionService.getPermissionByIds(preStr);
		role = roleDao.findOne(role.getId());
		for (Permissions per : permissions) {
			per.setRole(role);
			permissionService.update(per);
		}
		return null;
	}

	public void deleteRole(String roleId) {
		roleDao.deleteRole(roleId);
	}

	public Roles findOne(String roleId) {
		return roleDao.findOne(roleId);
	}

	public List<Roles> findAll() {
		return roleDao.findAll();
	}
	
	@Override
	public Page<Roles> getRolePage(String nowPage, String pageSize) {
		String hql = "from Roles";
		Integer pageNo = pasrePageNow(nowPage);
		Integer pageSizeInt = Integer.parseInt(pageSize);
		
		List<Roles> users = baseDao.find(hql, new Object[] {}, pageNo, pageSizeInt);
		long totalCount = baseDao.count(hql);

		Page<Roles> page = new Page<Roles>(pageSizeInt);
		page.setTotalCount(totalCount);
		page.setResult(users);
		page.setPageNo(pageNo);
		return page;
	}

	private Integer pasrePageNow(String nowPage) {
		if(null!=nowPage){
			Integer pageNo = Integer.parseInt(nowPage);
			return pageNo;
		}
		return 1;
	}
}
